package cn.itcast.batch.task;

import cn.itcast.batch.utils.MongoUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.LinkedList;

//自定义告警规则告警类型统计
public class AlarmTypeMongoTask {
    public static void main(String[] args) {
        /**
         * 1.获取MongoDB客户端链接对象
         * 2.获得被操作的数据库名称：itcast
         * 3.获取集合名称：collection
         * 4.sql实现数据聚合分析
         * 5.打印测试结果
         */
        //todo 1.获取MongoDB客户端链接对象
        MongoClient mongoClient = MongoUtil.getConnect();
        //todo 2.获得被操作的数据库名称：itcast
        MongoDatabase database = mongoClient.getDatabase("itcast");
        //todo 3.获取集合名称：collection
        MongoCollection<Document> collection = database.getCollection("custom_rule_alarm");
        //todo 4.sql实现数据聚合分析
        LinkedList<Document> aggregateList = new LinkedList<>();
        Document doc = new Document();
        doc.append("$group", BasicDBObject.parse("{\"_id\":{\"rule_name\":\"$rule_name\"},\"countNum\":{$sum:1}}"));
        aggregateList.add(doc);
        doc = new Document();
        doc.append("$sort",BasicDBObject.parse("{\"countNum\":-1}"));
        aggregateList.add(doc);
        MongoCursor<Document> mongoCursor = collection.aggregate(aggregateList).iterator();

        //todo 5.打印测试结果
        while (mongoCursor.hasNext()){
            System.out.println(mongoCursor.next());
        }


    }
}
